package com.red.wine.sql;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.os.Environment;

public class UserLog {
	// 日志文件保存的路径以及日志文件名
	String filePath = Environment.getExternalStorageDirectory().toString();
	String fileName = "/logfile.txt";// 巡检log
	private static UserLog instance;

	public synchronized static UserLog getInstance() {
		if (instance == null) {
			instance = new UserLog();
		}
		return instance;
	}

	/**
	 * 创建巡检日志文件
	 */
	public void createFile() {
		// 判断sd卡是否存在
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File dir = new File(filePath + fileName);
			// 如果文件不存在则创建新文件
			if (!dir.exists()) {
				try {
					dir.createNewFile();
				} catch (IOException e) {
					// 输入异常信息
					e.printStackTrace();
					write(e.toString());
				}
			}
		}
	}

	/**
	 * 写入巡检日志信息
	 * 
	 * @param content
	 */
	public void write(String content) {
		try {
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				File targetFile = new File(Environment
						.getExternalStorageDirectory().getCanonicalPath()
						+ fileName);
				// 以指定文件创建RandomAccessFile对象
				RandomAccessFile accessFile = new RandomAccessFile(targetFile,
						"rw");
				// 创建时间对象
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"
						+ " " + "hh:mm:ss");
				// 将文件记录指针移到最后
				accessFile.seek(targetFile.length());
				// 输出日志信息到文件中
				accessFile
						.write(("\n" + dateFormat.format(new Date()).toString()
								+ " : " + content).getBytes());
//				 accessFile.write("\r\t\n".getBytes());
				// 关闭文件
				accessFile.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			write(e.toString());
		}
	}

}
